import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import { Modal, Button ,Form, Input, Select, Tabs, Upload, Icon,message} from 'antd';

const Option = Select.Option;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const TextArea = Input.TextArea;

import api from '../api';

const formItemLayout = {
    labelCol: {
      sm: { span: 5 },
    },
    wrapperCol: {
      sm: { span: 16 },
    },
};

export default class FormInput extends React.Component {

    constructor(props,context) {
        super(props,context);
        this.state = {
            previewVisible: false,
            previewImage: '',
            fileList: [{
              uid: -1,
              name: 'xxx.png',
              status: 'done',
              url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
            }],
            jpgList: [],
            jpgListTW:[],
            curData: {
                reply_type: ''
            },
            curKeysData: {}
        };

        this.getActiveMap = {
            'text': '1',
            'image': '2',
            'news': '3',
            'voice': '4',
            'video': '5',
        }
    }

    //
    handleCancel(){
        this.setState({ previewVisible: false })
    }

    handlePreview(type,size,file){


        if (file.size) {
          const isLt2M = file.size / 1024 / 1024 < size;
          if (!isLt2M) {
          }else{
            this.setState({
              previewImage: file.response || file.thumbUrl,
              previewVisible: true
            });
          }
        }else{
          this.setState({
              previewImage: file.response || file.thumbUrl,
              previewVisible: true
            });
        }

        // let res = JSON.parse(file.response.data);
        // this.setState({
        //   previewImage: file.response,
        //   previewVisible: true,
        // });
    }

    handleChange(type,size,fileObj){

        if (fileObj.file.size / 1024 / 1024 > size) {
          this.setState({
            fileList:[],
          })

          return;
        }

        let {parent, keys} = this.props;
        let {curData, curKeysData} = parent.state;

        if (type == "image") {
          curData.jpgList = fileObj.fileList;
          // this.setState({
          //   jpgList: fileObj.fileList
          // });
        }else if (type == "news") {
          curData.jpgListTW = fileObj.fileList;
          // this.setState({
          //   jpgListTW: fileObj.fileList
          // });
        }else if (type == "voice") {//
          if (fileObj.fileList && fileObj.fileList.length > 0) {
            let files = []
            files.push(fileObj.fileList[fileObj.fileList.length-1])
            curData.voiceList = files;
            // this.setState({
            //   voiceList: files,
            // });
          }else{
            curData.voiceList = [];
            // this.setState({
            //   voiceList: []
            // });
          }
            
        }else if (type == "video") {
          if (fileObj.fileList && fileObj.fileList.length > 0) {
            let files = [];
            files.push(fileObj.fileList[fileObj.fileList.length-1])
            curData.videoList = files;
            // this.setState({
            //   videoList: files,
            // });
          }else{
            curData.videoList = [];
            // this.setState({
            //   videoList: []
            // });
          }
        }
        

        if(fileObj.file.status == 'done'){//上传完成后
            // let res = JSON.parse(fileObj.file.response.data);
            let res = fileObj.file.response;
            // let newKeysObj = {...curKeysData};

            // if(keys){//此分支暂时不用
            //     newKeysObj[keys] = {
            //         ...newKeysObj[keys],
            //         media_id: res.media_id?res.media_id:null,
            //         news_pic_url: res.url,
            //         reply_type: type
            //     }
            // }

            curData.reply_type = type;
            let {contentImage = ""} = parent.state;
            if (type == "news") {
              contentImage += res+";";
              curData.newsUrl = contentImage;
            }else if (type == "image") {
              curData.imageUrl = res;
            }else if (type == "voice") {
              curData.voiceUrl = res;
            }else if (type == "video") {
              curData.videoUrl = res;
            }


            
            parent.setState({
              contentImage, 
            });
        }
        parent.setState({
          curData:curData,
        })

    }

    beforUpload(size,file){
      var s = parseInt(size);
      const isLt2M = file.size / 1024 / 1024 < s;
      if (!isLt2M) {
        message.error('文件大小不能超过'+size+'M');
      }
      return isLt2M;
    }


    onChange(activeKey){
        let {parent, keys} = this.props;
        let {curData, curKeysData} = parent.state;


        if(typeof activeKey == 'object'){
            if(activeKey.target.tagName.toLowerCase() == 'textarea'){//是textarea
                // let newKeysObj = {...curKeysData};
                // if(keys){
                //     newKeysObj[keys] = {
                //         ...newKeysObj[keys],
                //         content: activeKey.target.value,
                //         reply_type: 'text'
                //     }
                // }
                curData.textContent = activeKey.target.value;
                curData.reply_type = "text",
                parent.setState({
                    curData:curData,
                    // curKeysData:newKeysObj
                });
            }else{
                let newObj = null; 
                // newKeysObj = {...curKeysData};
                if(activeKey.target.id == 'news_title'){
                    newObj = {newsTitle:activeKey.target.value,reply_type:"news"};
                }else if (activeKey.target.id == 'news_disp') {
                    newObj = {newsDescription:activeKey.target.value,reply_type:"news"};
                }else if (activeKey.target.id == 'url') {//图文
                    newObj = {newsGotoUrl:activeKey.target.value,reply_type:"news"};
                }else if (activeKey.target.id == 'video_title') {
                    newObj = {videoTitle:activeKey.target.value,reply_type:"video"};
                }else if (activeKey.target.id == 'video_disp') {
                    newObj = {videoDescription:activeKey.target.value,reply_type:"video"};
                }

                // if(keys){
                //     newKeysObj[keys] = {
                //         ...newKeysObj[keys],
                //         ...newObj
                //     }
                // }
                curData = {...curData,...newObj};
                parent.setState({
                    curData:curData,
                });
            }

        }else{

            parent.setState({
                curData:{
                    ...curData,
                    reply_type: activeKey
                }
            });
        }

    }

    add = (type) => {

    }

    componentWillReceiveProps(nextProps){
        // this.forceUpdate();
    }

    render(){
        const { previewVisible, previewImage, fileList, jpgList ,jpgListTW,voiceList,videoList} = this.state;

        let {parent, curData} = this.props;
        if(!curData){
            curData = {};
        }


        return (
            <Tabs defaultActiveKey={curData.reply_type?curData.reply_type:'text'} animated={false} onChange={this.onChange.bind(this)}>
                <TabPane tab={<span><Icon type="file-text" />文字</span>} key="text">
                    <TextArea placeholder="直接开始输入..." rows={4} value={curData.reply_type == "text" ? curData.textContent : ""} onChange={this.onChange.bind(this)}/>
                </TabPane>

                <TabPane tab={<span><Icon type="file-jpg" />图片</span>} key="image">
                    <div className="clearfix">
                        <Upload
                          action="/file/upload-file"
                          listType="picture-card"
                          fileList={curData.jpgList}
                          accept="image/*"
                          data={{
                              type: 'image'
                          }}
                          onPreview={this.handlePreview.bind(this,'image',1)}
                          onChange={this.handleChange.bind(this,'image',1)}
                          beforeUpload={this.beforUpload.bind(this,1)}
                        >
                          {curData.jpgList && curData.jpgList.length >= 1 ? null : <div>
                              <Icon type="plus" />
                              <div className="ant-upload-text">添加图片</div>
                          </div>}
                        </Upload>
                        
                        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel.bind(this,'image')}>
                          <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                     </div>
                     <div>1M,支持png/jpeg/jpg格式</div>
                </TabPane>
                <TabPane tab={<span><Icon type="calculator" />图文</span>} key="news">
                    <div className="clearfix">
                        <Input addonBefore="消息标题" defaultValue="" placeholder="请输入消息标题" value={curData.reply_type == 'news'?curData.newsTitle:''} onChange={this.onChange.bind(this)} id="news_title"/>
                        <Input addonBefore="消息描述" defaultValue="" placeholder="请输入消息描述" value={curData.reply_type == 'news'?curData.newsDescription:''} onChange={this.onChange.bind(this)} id="news_disp"/>
                        <div>添加点击链接：</div>
                        <Input addonBefore="点击链接" defaultValue="" placeholder="请输入点击链接" value={curData.reply_type == 'news'?curData.newsGotoUrl:''} onChange={this.onChange.bind(this)} id="url"/>
                        <div>添加图片：</div>
                        <Upload
                          action="/file/upload-file"
                          listType="picture-card"
                          accept="image/*"
                          fileList={curData.jpgListTW && curData.jpgListTW.length==0&&curData.news_pic_url&&curData.reply_title?[{
                            uid: -1,
                            status: 'done',
                            url: curData.news_pic_url,
                        }]:curData.jpgListTW}
                          data={{
                              type: ''
                          }}
                          onPreview={this.handlePreview.bind(this,'news',1)}
                          onChange={this.handleChange.bind(this,'news',1)}
                          beforeUpload={this.beforUpload.bind(this,1)}
                        >
                          {curData.jpgListTW && curData.jpgListTW.length >= 1 ? null : <div>
                              <Icon type="plus" />
                              <div className="ant-upload-text">添加图片</div>
                          </div>
                        }
                        </Upload>
                        
                     </div>
                     <div>1M,支持png/jpeg/jpg格式</div>
                </TabPane>
              {/*先将语音和视频消息隐藏掉 先注释掉，勿删*/}
                {/*<TabPane tab={<span><Icon type="sound" />语音</span>} key="voice">
                    <div className="clearfix">
                        <Upload
                          action="/file/upload-file"
                          accept="audio/mp3,audio/wma,audio/wav,audio/amr"
                          fileList={curData.voiceList}
                          data={{
                              type: 'voice'
                          }}
                          onChange={this.handleChange.bind(this,'voice',2)}
                          beforeUpload={this.beforUpload.bind(this,2)}
                        >
                          <div>
                            <Button type="primary">
                              <Icon type="upload" />添加语音
                            </Button>
                            
                            
                          </div>
                        </Upload>
                        
                     </div>
                     <div>2M，播放长度不超过60s，mp3/wma/wav/amr格式</div>
                </TabPane>*/}
                {/*<TabPane tab={<span><Icon type="play-circle-o" />视频</span>} key="video">
                    <div className="clearfix">
                        <Input addonBefore="消息标题" defaultValue="" placeholder="请输入消息标题" value={curData.reply_type == 'video'?curData.videoTitle:''} onChange={this.onChange.bind(this)} id="video_title"/>
                        <Input addonBefore="消息描述" defaultValue="" placeholder="请输入消息描述" value={curData.reply_type == 'video'?curData.videoDescription:''} onChange={this.onChange.bind(this)} id="video_disp"/>
                        <div>添加视频：</div>
                        <Upload
                          action="/file/upload-file"
                          accept="video/mp4"
                          fileList={curData.videoList}
                          data={{
                              type: 'video'
                          }}
                          onChange={this.handleChange.bind(this,'video',10)}
                          beforeUpload={this.beforUpload.bind(this,10)}
                        >
                          <div>
                            <Button type="primary">
                              <Icon type="upload" />添加视频
                            </Button>
                          </div>
                        </Upload>
                        
                     </div>
                     <div>10MB，支持MP4格式</div>
                </TabPane>*/}
            </Tabs>
        );
    }
}

FormInput.contextTypes= { router: React.PropTypes.object.isRequired};
